//
//  DataTool.m
//  Marketing
//
//  Created by wmm on 16/2/26.
//  Copyright © 2016年 Hanen 3G 01. All rights reserved.
//

#import "DataTool.h"

@implementation DataTool

+ (void)sendGetWithUrl:(NSString *)url parameters:(NSDictionary *)dict success:(SuccessBlock)successblock fail:(FailBlock)failblock
{
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//    [manager GET:url parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
//                successblock(responseObject);
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        failblock(error);
//    }];
}

+ (void)postWithUrl:(NSString *)url parameters:(NSDictionary *)dict success:(SuccessBlock)successBlock fail:(FailBlock)faileBlock
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 30.0f;
    manager.requestSerializer = [AFHTTPRequestSerializer serializer]; // 上传普通格式
    // 声明获取到的数据格式
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    [manager POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"成功");
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSString *status = [(NSDictionary *)jsonDic objectForKey:@"status"];
        NSString *userToken;
        if (![(NSDictionary *)jsonDic objectForKey:@"data"]){
            if (![[(NSDictionary *)jsonDic objectForKey:@"data"] objectForKey:@"userToken"]) {
                userToken = [[(NSDictionary *)jsonDic objectForKey:@"data"] objectForKey:@"userToken"];
            }
        }
        int code = [[(NSDictionary *)jsonDic objectForKey:@"code"] intValue];
        NSString *msg = [(NSDictionary *)jsonDic objectForKey:@"msg"];
        NSLog(@"返回%@%d%@",status,code,msg);
        if (code == 899999) {
            if (userToken == nil) {
                //创建一个消息对象
                NSNotification * notice = [NSNotification notificationWithName:@"userToken" object:nil userInfo:@{@"userToken":msg}];
                //发送消息
                [[NSNotificationCenter defaultCenter] postNotification:notice];
                return;
            }
        }
        successBlock(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"失败");
        faileBlock(error);
    }];
}

//上传图片
+ (void)uploadPic:(NSData *)picData success:(SuccessBlock)successBlock fail:(FailBlock)faileBlock{
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
    [dictionary setObject:@"app.upload.store" forKey:@"method"];
    [dictionary setObject:@"jpeg" forKey:@"type"];
    [dictionary setObject:[picData base64Encoding] forKey:@"data"];
    
    [self postWithUrl:HEAD_URL parameters:[DataTool addSignToDic:dictionary] success:^(id data) {
    NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        successBlock(jsonDic);
    } fail:^(NSError *error) {
        NSLog(@"error:%@",error);
        faileBlock(error);
    }];
}

+ (NSString*)getmd5WithString:(NSString *)string

{
    
    const char* original_str=[string UTF8String];
    
    unsigned char digist[CC_MD5_DIGEST_LENGTH]; //CC_MD5_DIGEST_LENGTH = 16
    
    CC_MD5(original_str, strlen(original_str), digist);
    
    NSMutableString* outPutStr = [NSMutableString stringWithCapacity:10];
    
    for(int  i =0; i<CC_MD5_DIGEST_LENGTH;i++){
        
        [outPutStr appendFormat:@"%02X", digist[i]];// 小写 x 表示输出的是小写 MD5 ，大写 X 表示输出的是大写 MD5
        
    }
    
    return outPutStr;
    
}

+ (NSComparisonResult)compareArray: (NSDictionary *)otherDictionary
{
    NSDictionary *tempDictionary = (NSDictionary *)self;
    
    int number1 = [[[tempDictionary allKeys] objectAtIndex:0] characterAtIndex:0]; //65
    int number2 = [[[otherDictionary allKeys] objectAtIndex:0] characterAtIndex:0];
//    NSNumber *number1 = [[tempDictionary allKeys] objectAtIndex:0];
//    NSNumber *number2 = [[otherDictionary allKeys] objectAtIndex:0];
    
    NSNumber *numObj1 = [NSNumber numberWithInt:number1];
    NSNumber *numObj2 = [NSNumber numberWithInt:number2];
    
    NSComparisonResult result = [numObj1 compare:numObj2];
    
    return result == NSOrderedDescending; // 升序
    //    return result == NSOrderedAscending;  // 降序
}

+ (NSMutableDictionary *)addSignToDic:(NSMutableDictionary *)dictionary{
    
    [dictionary setObject:@"yeguan" forKey:@"app_key"];
    [dictionary setObject:@"json" forKey:@"format"];
    [dictionary setObject:[DateTool getCurrentDate] forKey:@"timestamp"];

//    if (![[dictionary objectForKey:@"method"] isEqualToString:@"app.user.login"]){
//        [dictionary setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"userToken"] forKey:@"userToken"];
//    }
    
    NSString *method = [dictionary objectForKey:@"method"];
    NSLog(@"%@",method);
    if (![method isEqualToString:@"app.user.login"]) {
        [dictionary setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"userToken"] forKey:@"userToken"];
    }

    NSArray *myKeys = [dictionary allKeys];
    NSArray *newArray = [myKeys sortedArrayUsingSelector:@selector(compare:)];
    NSString *str1 = @"YUNGUI";
    for (NSString *key in newArray) {
        str1 = [NSString stringWithFormat:@"%@%@%@", str1, key ,[dictionary objectForKey:key]];
    }
    str1 = [NSString stringWithFormat:@"%@YUNGUI", str1];
    
    NSString *sign = [self getmd5WithString:str1];
    [dictionary setObject:sign forKey:@"sign"];
    NSLog(@"sign-dictionary:%@",dictionary);//代码注释之后创建小区不能创建？？？？？？？？
    
    return dictionary;
}

#pragma mark - 私有方法
//将NSDictionary中的Null类型的项目转化成@""
+(NSDictionary *)nullDic:(NSDictionary *)myDic
{
    NSArray *keyArr = [myDic allKeys];
    NSMutableDictionary *resDic = [[NSMutableDictionary alloc]init];
    for (int i = 0; i < keyArr.count; i ++)
    {
        id obj = [myDic objectForKey:keyArr[i]];
        
        obj = [self changeType:obj];
        
        [resDic setObject:obj forKey:keyArr[i]];
    }
    return resDic;
}

//将NSDictionary中的Null类型的项目转化成@""
+(NSArray *)nullArr:(NSArray *)myArr
{
    NSMutableArray *resArr = [[NSMutableArray alloc] init];
    for (int i = 0; i < myArr.count; i ++)
    {
        id obj = myArr[i];
        
        obj = [self changeType:obj];
        
        [resArr addObject:obj];
    }
    return resArr;
}

//将NSString类型的原路返回
+(NSString *)stringToString:(NSString *)string
{
    return string;
}

//将Null类型的项目转化成@""
+(NSString *)nullToString
{
    return @"";
}

#pragma mark - 公有方法
//类型识别:将所有的NSNull类型转化成@""
+(id)changeType:(id)myObj
{
    if ([myObj isKindOfClass:[NSDictionary class]])
    {
        return [self nullDic:myObj];
    }
    else if([myObj isKindOfClass:[NSArray class]])
    {
        return [self nullArr:myObj];
    }
    else if([myObj isKindOfClass:[NSString class]])
    {
        return [self stringToString:myObj];
    }
    else if([myObj isKindOfClass:[NSNull class]])
    {
        return [self nullToString];
    }
    else
    {
        return myObj;
    }
}


//URLENcode
+ (NSString*)encodeString:(NSString*)unencodedString{
    
    // CharactersToBeEscaped = @":/?&=;+!@#$()~',*";
    // CharactersToLeaveUnescaped = @"[].";
    
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)unencodedString,
                                                              NULL,
                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                              kCFStringEncodingUTF8));
    
    return encodedString;
}

//URLDEcode
+ (NSString *)decodeString:(NSString*)encodedString

{
    //NSString *decodedString = [encodedString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding ];
    
    NSString *decodedString  = (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,
                                                                                                                     (__bridge CFStringRef)encodedString,
                                                                                                                     CFSTR(""),
                                                                                                                     CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    return decodedString;
}

@end
